﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.BusinessEntity.BusinessFlow;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.OperationWebService;
using Kingdee.BOS.Core.DynamicService;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.DataEntity.Metadata.Service;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.Client;
using LiMinCRMPlugin.InterfaceDocking;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Security.Cryptography;



namespace LiMinCRMPlugin
{
    /// <summary>
    /// 
    /// </summary>
    /// <remarks>
    /// 功能：
    /// 创建人：wzx
    /// 创建日期：2024/9/3
    /// </remarks>
    /// 
    [Description("自动执行计划查询未生成待认领收款的银行流水")]
    [HotUpdate]
    public class BankStatementExecutionPlan : IScheduleService
    {
        public void Run(Context ctx, Schedule schedule)
        {

            #region 所有未生成待认领收款的银行流水
            string sql_PO = string.Format(@"/*dialect*/select * from T_CN_BANKCASHFLOW where F_RDLV_GenerateStatus='0' and FPAYORGID='100082' and FCREDITAMOUNT>0 and FBANKACNTNO <>'516900120710888'");//招商网银不生成
            DataTable dt_PO = DBUtils.ExecuteDataSet(ctx, sql_PO).Tables[0];
            if (dt_PO.Rows.Count > 0)
            {
                foreach (DataRow PO in dt_PO.Rows)
                {
                    string FID = Convert.ToString(PO["FID"]);//内码
                    string SETTLENO = Convert.ToString(PO["FSETTLENO"]);//银企流水号
                    string BNKSEQNO = Convert.ToString(PO["FBNKSEQNO"]);//银行流水号
                    string TRANSDATE = Convert.ToString(PO["FTRANSDATE"]);//交易日期
                    string PAYORGID= Convert.ToString(PO["FPAYORGID"]);//收付组织
                    string FBillNo = Convert.ToString(PO["FBillNo"]);//单据编码


                    decimal CREDITAMOUNT = 0;
                    CREDITAMOUNT = Convert.ToDecimal(PO["FCREDITAMOUNT"]);//贷方-收款金额
                    string ACCOUNTID = Convert.ToString(PO["FACCOUNTID"]);//收款银行账号
                    string PAYUNITID = Convert.ToString(PO["FSETTLETYPEID"]);//结算方式
                    string BANKACNTNO = Convert.ToString(PO["FBANKACNTNO"]);//银行账号编码

                    string CurrencyNO = "";//币别 

                    CurrencyNO = Convert.ToString(PO["FCurrency"]);

                    string OppBankAcntName = Convert.ToString(PO["FOppBankAcntName"]);//对方账户名称
                    string OppBankAcntNo = Convert.ToString(PO["FOppBankAcntNo"]);//对方银行账号
                    string OppOpenBankName = Convert.ToString(PO["FOppOpenBankName"]);//对方开户行
                   //是收款的明细
                    if (CREDITAMOUNT > 0 && OppBankAcntName != "利民控股集团股份有限公司"
                         && OppBankAcntName != "利民化学有限责任公司" && OppBankAcntName != "河北威远生物化工有限公司"
                         && OppBankAcntName != "内蒙古新威远生物化工有限公司" && OppBankAcntName != "河北双吉化工有限公司"
                         && OppBankAcntName != "中国证券登记结算有限责任公司深圳分公司")
                    {
                        K3CloudApiClient client = new K3CloudApiClient("http://10.10.11.100/K3Cloud/");
                        string loginResult = client.LoginByAppSecret(
                        "6642ecc879eb25",//账套
                        "Administrator",//用户名
                        "278414_Q/dDxcEL5MmaR/8p453Dy99EQq3bToLG",//应用ID
                        "ccecc8d0a50d4fdcb51e2684ee906248",//应用秘钥
                        2052 //中文
                        );                 

                        Newtonsoft.Json.Linq.JObject loginResultObj = JObject.Parse(loginResult);

                        JToken loginResultType;

                        loginResultObj.TryGetValue("LoginResultType", out loginResultType);
                        if (loginResultType != null && loginResultType.Value<Int32>() == 1)
                        {
                            #region JSON
                            // 获取保存Json
                            var saveStr = BuildUploadObj(ctx);
                            // 转成JObject
                            JObject saveObj = JObject.Parse(saveStr);
                            //删除不需要传值的字段
                            JObject JO = (JObject)saveObj["Model"];
                            JO.Remove("F_QLTK_ExchangeRate");//汇率
                            JO.Remove("F_DEV_FDATE");//同步CRM日期
                            saveObj["ValidateRepeatJson"] = "true";//校验Json数据包是否重复传入，一旦重复传入，接口调用失败（10分钟内）
                            // 获取Model
                            JToken modelObj = JO;
                            // 设值
                            JObject basedata = new JObject();
                            basedata.Add("FOrgID", PAYORGID);
                            modelObj["F_RDLV_OrgId_83g"] = basedata;//组织
                            modelObj["F_RDLV_SerialNumber"] = BNKSEQNO;//流水号
                            modelObj["F_RDLV_TradingDay"] = TRANSDATE;//交易日
                            modelObj["F_RDLV_Amount"] = CREDITAMOUNT;//交易金额
                            basedata = new JObject();
                            basedata.Add("FNUMBER", BANKACNTNO);
                            modelObj["F_RDLV_Base_w5c"] = basedata;//收款银行账号
                            basedata = new JObject();
                            basedata.Add("FNumber", "JSFS04_SYS");
                            modelObj["F_RDLV_SettleType"] = basedata;//结算方式
                            basedata = new JObject();
                            basedata.Add("FNumber", CurrencyNO);
                            modelObj["F_RDLV_CurrencyType"] = basedata;//币别
                            modelObj["F_RDLV_PayerAccount"] = OppBankAcntName;//付款方账户名称
                            modelObj["F_RDLV_PayerBankAccount"] = OppBankAcntNo;//付款方银行账号
                            modelObj["F_RDLV_PayerOpenBank"] = OppOpenBankName;//付款方开户行
                            modelObj["F_RDLV_CDQFR"] = "";//承兑签发日
                            modelObj["F_RDLV_CDDQR"] = "";//承兑到期日

                            basedata = new JObject();
                            basedata.Add("FNumber", "CNY");
                            modelObj["F_QLTK_BaseCurrency"] = basedata;//本位币
                            basedata = new JObject();
                            basedata.Add("FNumber", "HLTX01_SYS");
                            modelObj["F_QLTK_Exchange"] = basedata;//汇率类型
                            modelObj["F_QLTK_TradingCode"] = FBillNo;//交易编码


                            #endregion
                            var R = client.Save("RDLV_PendingCollectionList", Convert.ToString(saveObj));
                            Common.ResultObject resultObject = JsonConvert.DeserializeObject<Common.ResultObject>(R);
                            string IsSuccess = resultObject.result.responseStatus.IsSuccess;
                            string RNumber = Convert.ToString(resultObject.result.number);
                            string RID = Convert.ToString(resultObject.result.id);
                            string ErrorMessage = "";
                            if (resultObject.result.responseStatus.Errors.Length > 0)
                            {
                                for (int i = 0; i < resultObject.result.responseStatus.Errors.Length; i++)
                                {
                                    ErrorMessage = ErrorMessage + "(" + i.ToString() + ")" + resultObject.result.responseStatus.Errors[i].FieldName + resultObject.result.responseStatus.Errors[i].Message + ";\t";
                                }
                            }
                            bool bIsSuccess = Convert.ToBoolean(IsSuccess);
                            if (bIsSuccess)//如果保存成功
                            {
                                //var S=client.Submit("RDLV_PendingCollectionList", "{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\""+ RID + "\",\"SelectedPostId\":0,\"UseOrgId\":0,\"NetworkCtrl\":\"\",\"IgnoreInterationFlag\":\"\"}");
                                //Common.ResultObject resultObjectS = JsonConvert.DeserializeObject<Common.ResultObject>(S);
                                //string IsSuccessS = resultObjectS.result.responseStatus.IsSuccess;
                                //if (Convert.ToBoolean(IsSuccessS))
                                //{
                                //    client.Audit("RDLV_PendingCollectionList", "{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\""+ RID + "\",\"InterationFlags\":\"\",\"UseOrgId\":0,\"NetworkCtrl\":\"\",\"IsVerifyProcInst\":\"true\",\"IgnoreInterationFlag\":\"\",\"UseBatControlTimes\":\"false\"}");
                                //} 
                                string SQL = string.Format(@"update  T_CN_BANKCASHFLOW set F_RDLV_GenerateStatus=1 where FID='{0}'", FID);
                                DBUtils.Execute(ctx, SQL);
                            }
                            else
                            {        
                                string SQL = string.Format(@"update  T_CN_BANKCASHFLOW set F_RDLV_GenerateStatus=0 where FID='{0}'", FID);
                                DBUtils.Execute(ctx, SQL);
                            }
                            #region 待认领清单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                            interfaceLog.FBILLNO = SETTLENO;
                            interfaceLog.FBILLID = FID;
                            interfaceLog.FDATE = System.DateTime.Now;
                            interfaceLog.FINTERNAME = "银企流水生成待认领";
                            interfaceLog.FInvokeType = "待认领清单新增";
                            interfaceLog.Ftoken = "";
                            if (bIsSuccess)
                            {
                                interfaceLog.FSTATUS = "成功";
                            }
                            else
                            {
                                interfaceLog.FSTATUS = "失败";
                            }
                            
                            interfaceLog.FRequsetData = Convert.ToString(saveObj);
                            interfaceLog.FReturnData = ErrorMessage;
                            interfaceLog.FRequest = Convert.ToString(saveObj);
                            interfaceLog.FReturn = ErrorMessage;
                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                            List<string> sqlList = new List<string>();
                            if (!string.IsNullOrEmpty(LogSql))
                            {
                                sqlList.Add(LogSql);
                            }
                          
                            DBServiceHelper.ExecuteBatch(ctx, sqlList);

                            #endregion
                        }
                        else//登陆失败
                        {
                            string SQL = string.Format(@"update  T_CN_BANKCASHFLOW set F_RDLV_GenerateStatus=0 where FID='{0}'", FID);
                            DBUtils.Execute(ctx, SQL);
                            #region 待认领清单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                            interfaceLog.FBILLNO = SETTLENO;
                            interfaceLog.FBILLID = FID;
                            interfaceLog.FDATE = System.DateTime.Now;
                            interfaceLog.FINTERNAME = "银企流水生成待认领";
                            interfaceLog.FInvokeType = "待认领清单新增";
                            interfaceLog.Ftoken = "";
                            interfaceLog.FSTATUS = "失败";
                            interfaceLog.FRequsetData = null;
                            interfaceLog.FReturnData = "登陆失败";
                            interfaceLog.FRequest =null;
                            interfaceLog.FReturn = "登陆失败";
                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                            List<string> sqlList = new List<string>();
                            if (!string.IsNullOrEmpty(LogSql))
                            {
                                sqlList.Add(LogSql);
                            }

                            DBServiceHelper.ExecuteBatch(ctx, sqlList);

                            #endregion
                        }
                    }
                }
            }
            }




            #endregion
        
        // 获取Json的方法类
        private static string BuildUploadObj(Context context)
        {
            // SaveDesigner为保存操作的设计组件，其他操作请查询T_MDL_FormOperationType 表格
            var designType = TypesContainer.GetOrRegister("Kingdee.BOS.Business.Bill.OperationService.SaveDesigner,Kingdee.BOS.Business.Bill");
            var designer = Activator.CreateInstance(designType) as OperationWebServiceDesigner;
            designer.OperationId = "Save";
            designer.IsWebApi = true;

            var meta = FormMetaDataCache.GetCachedFormMetaData(context, "RDLV_PendingCollectionList");
            var model = designer.CreateServiceModel(context, meta, null) as FormServiceModel;


            // WebApiParamHelper 为内部封装WebApi帮助类，没有对外发布，需要用发射调用获取JSON
            var webApiHelperClass =
                "Kingdee.BOS.Business.PlugIn.DynamicService.WebApiParamHelper,Kingdee.BOS.Business.PlugIn";
            var webApiHelperType = TypesContainer.GetOrRegister(webApiHelperClass);
            var webApiHelper = Activator.CreateInstance(webApiHelperType);
            var getJsonData = webApiHelperType.GetMethod("GetJSONData", new Type[] { typeof(DTOType), typeof(Boolean) });
            return getJsonData?.Invoke(webApiHelper, new object[] { model?.RequestDTOType, true }).GetString();
        }

    }
}
